import socket
import sys

def send_command(command: str, host: str = "192.168.1.xxx", port: int = 8080):
    """
    发送命令到ESP32设备
    
    参数:
        command: 要发送的命令 ('1'-'8' 控制对应LED, 'Q' 关闭所有LED)
        host: ESP32的IP地址
        port: UDP端口号(默认8080)
    """
    try:
        # 创建UDP socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        
        # 发送命令
        sock.sendto(command.encode(), (host, port))
        
    except Exception as e:
        print(f"发送失败: {e}")
    finally:
        sock.close()

def main():
    if len(sys.argv) != 2:
        print("使用方法: python script.py <ESP32_IP>")
        sys.exit(1)
    
    host = sys.argv[1]
    
    print("LED控制程序")
    print("命令说明:")
    print("1-8: 切换对应LED的开关状态")
    print("Q: 关闭所有LED并退出")
    print("输入'exit'退出程序")
    
    while True:
        command = input("请输入命令: ").strip().upper()
        
        if command == 'EXIT':
            break
            
        if command in ['1', '2', '3', '4', '5', '6', '7', '8', 'Q']:
            send_command(command, host)
        else:
            print("无效命令！请输入1-8或Q")

if __name__ == "__main__":
    main()